package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 李旭
 * @date 2022/1/15 15:21
 * @Description:
 */
@RestController
@RequestMapping("/api/user/passport")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @PostMapping("/login")
    public Result login(@Validated @RequestBody UserInfo userInfo){


        //校验用户名密码是否正确
        userInfo = userInfoService.checkInfo(userInfo);

        if(null != userInfo){
            //正确的
            String uuid = UUID.randomUUID().toString();
            Map map = new HashMap<>();
            map.put("token", uuid);
            map.put("nickName", userInfo.getNickName());

            redisTemplate.opsForValue().set(
                    RedisConst.USER_LOGIN_KEY_PREFIX + uuid,userInfo.getId().toString());
            //颁发令牌 UUID
            return Result.ok(map);
        }
        return Result.fail().message("用户名或密码是不正确的");
    }
    //查询当前用户的所有收货地址集合
    @GetMapping("/getUserAdderess")
    public List<UserAddress> getUserAdderess(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userInfoService.getUserAdderess(userId);
    }
}
